package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;


/**
 * @author cxt
 * &#064;Description 自定义ConverterFactory[实现从String到BaseEnum(父枚举类型的)的转换]
 * &#064;create 2025/3/15 下午4:56
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                T[] values = targetType.getEnumConstants();
                for (T value : values) {
                    if (value.getCode().equals(Integer.valueOf(source))) {
                        return value;
                    }
                }
                throw new IllegalArgumentException(String.format("type [%s] 错误", source));
            }
        };
    }
}

